import './dlg.css';

export class Dialog extends HTMLElement {
  constructor(dlgName) {
    super();
    this.#dlgName = dlgName;
    this.#init();

    this.#$btnClose.onclick = this.#onClose.bind(this);
    this.#$titlebar.onmousedown = (e) => {
      this.#isDragging = true;
      this.#startX = e.pageX;
      this.#startY = e.pageY;
      this.#dlgX = this.#$dlg.offsetLeft;
      this.#dlgY = this.#$dlg.offsetTop;
    };
    document.body.addEventListener('mousemove',(e)=>{
      if(!this.#isDragging) return;

      const offsetX = e.pageX - this.#startX;
      const offsetY = e.pageY - this.#startY;

      this.#$dlg.style.left = (this.#dlgX + offsetX) + 'px';
      this.#$dlg.style.top = (this.#dlgY + offsetY) + 'px';

    });

    document.body.addEventListener('mouseup', (e) => {
      this.#isDragging = false;
    });

  }
  #init(){
    this.innerHTML = this.#html;
    this.$ = this.querySelector;

    this.#$btnClose = this.$('.close');
    this.#$titlebar = this.$('.titlebar');
    this.#$dlg = this.$('.dialog');
    this.#$dlgMain = this.$('.main');
    this.#$title = this.$('.title');

    this.#restore();
  }
  decorate(html,title) {
    this.#$title.innerText = title;
    this.#$dlgMain.innerHTML = html;
  }
  #onClose() {
    localStorage[this.#dlgName + '-top'] = this.#$dlg.offsetTop;
    localStorage[this.#dlgName + '-left'] = this.#$dlg.offsetLeft;
    this.remove();
  }
  #restore() {
    this.#$dlg.style.top = (localStorage[this.#dlgName + '-top'] || 100) + 'px';
    this.#$dlg.style.left = (localStorage[this.#dlgName + '-left'] || 100) + 'px';
  }
  #$btnClose = null;
  #$titlebar = null;
  #$title = null;
  #$dlg = null;
  #$dlgMain = null;
  #isDragging = false;
  #startX = 0;
  #startY = 0;
  #dlgX = 0;
  #dlgY = 0;
  #dlgName = '';
  #html = ''
  + '<div class="mask">'
    + '<div class="dialog">'
      + '<div class="titlebar">'
        +'<span class="title"></span>'
        +'<span class="close" title="关闭">✖ </span>'
      +'</div>'
      + '<div class="main">'
        + '</div>'
    + '</div>'
  + '</div>'

}



